﻿using Microsoft.Xrm.Client.Services;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TesterCRM.Auxiliary
{
    class Connection
    {
        /// <summary>
        /// Checks and obtains the connection string to create the webservice from App.config.
        /// If there are more than a connection, it shows the others to choose one.
        /// </summary>
        /// <returns>An string with the webservice connection info.</returns>
        public static String GetServiceConfiguration ()
        {
            // Get available connection strings from app.config.
            int count = ConfigurationManager.ConnectionStrings.Count;

            // Create a filter list of connection strings so that we have a list of valid
            // connection strings for Microsoft Dynamics CRM only.
            List<KeyValuePair<String, String>> filteredConnectionStrings = new List<KeyValuePair<String, String>>();

            for (int a = 0; a < count; a++)
            {
                if (isValidConnectionString(ConfigurationManager.ConnectionStrings[a].ConnectionString))
                    filteredConnectionStrings.Add (
                        new KeyValuePair<string, string>(ConfigurationManager.ConnectionStrings[a].Name,
                            ConfigurationManager.ConnectionStrings[a].ConnectionString));
            }
            
            switch (filteredConnectionStrings.Count) 
            {
                case 0:                 // No valid connections strings found. Write out and error message.
                    return null;
                case 1:                 // If one valid connection string is found, use that.
                    return filteredConnectionStrings[0].Value;
                default:  // If more than one valid connection string is found, let the user decide which to use.
                    if (filteredConnectionStrings.Count >= 2)
                    {

                        Console.WriteLine("The following connections are available:");
                        Console.WriteLine("------------------------------------------------");

                        for (int i = 0; i < filteredConnectionStrings.Count; i++)
                        {
                            Console.Write("\n({0}) {1}\t",
                            i + 1, filteredConnectionStrings[i].Key);
                        }

                        Console.WriteLine();
                        Console.Write("\nType the number of the connection to use (1-{0}) [{0}] : ", 
                            filteredConnectionStrings.Count);
                        String input = Console.ReadLine();

                        int configNumber;
                        if (input == String.Empty) input = filteredConnectionStrings.Count.ToString();
                        if (!Int32.TryParse(input, out configNumber) || configNumber > count ||
                            configNumber == 0)
                        {
                            Console.WriteLine("Option not valid.");
                            return null;
                        }

                        return filteredConnectionStrings[configNumber - 1].Value;
                    }
                    else
                    {
                        return null;
                    }
            }
        }

        /// <summary>
        /// Obtains the connection string to create the webservice through his connection name.
        /// </summary>
        /// <param name="connectionName">Connection name to look for his connection string.</param>
        /// <returns>An string with the webservice connection info.</returns>
        public static String GetServiceConfiguration (string connectionName)
        {
            // Get available connection strings from app.config.
            int count = ConfigurationManager.ConnectionStrings.Count;
            
            List<KeyValuePair<String, String>> filteredConnectionStrings = new List<KeyValuePair<String, String>>();

            for (int a = 0; a < count; a++)
            {
                if (isValidConnectionString(ConfigurationManager.ConnectionStrings[a].ConnectionString))
                    filteredConnectionStrings.Add (
                        new KeyValuePair<string, string>(ConfigurationManager.ConnectionStrings[a].Name,
                            ConfigurationManager.ConnectionStrings[a].ConnectionString));
            }

            foreach ( var cs in filteredConnectionStrings )
            {
                if ( cs.Key == connectionName )
                    return cs.Value;
            }

            return null;
        }

        /// <summary>
        /// Verifies if a connection string is valid for Microsoft Dynamics CRM.
        /// </summary>
        /// <returns>True for a valid string, otherwise False.</returns>
        public static Boolean isValidConnectionString ( String connectionString )
        {
            // At a minimum, a connection string must contain one of these arguments.
            if (connectionString.Contains("Url=") ||
                connectionString.Contains("Server=") ||
                connectionString.Contains("ServiceUri="))
                return true;

            return false;
        }
    }
}
